from django.contrib.auth.models import Permission, ContentType, Group
from rest_framework import serializers

from userapp.models import Users


class PermissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = '__all__'

class ContentTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContentType
        fields = ['id','name']

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = '__all__'


class AdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = Users
        fields = '__all__'
        extra_kwargs = {
            'password':{
                'write_only':True
            }
        }

    def create(self, validated_data):
        # 新增管理员
        validated_data['is_staff'] = True
        admin = super(AdminSerializer, self).create(validated_data)
        admin.set_password(validated_data['password'])
        admin.save()

        return admin

    def update(self, instance, validated_data):
        # 修改管理员信息
        admin = super(AdminSerializer, self).update(instance,validated_data)
        admin.set_password(validated_data.get('password',instance.password))
        admin.save()

        return admin